package com.baizhi.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baizhi.common.exception.Assert;
import com.baizhi.common.result.R;
import com.baizhi.common.result.ResponseEnum;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@CrossOrigin(origins ="*",allowCredentials="true",
        allowedHeaders = "*",methods = {RequestMethod.POST,RequestMethod.GET})
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;


    @ApiOperation(value = "用户登录")
    @PostMapping("/user/login")
    public R login(
            @ApiParam(value = "用户对象",required = true)
            @RequestBody User user
    ){
        log.info("用户名: [{}]",user.getName());
        log.info("密码: [{}]",user.getPassword());
        try{
            User userDB = userService.login(user);
            Map<String,String> payload =  new HashMap<>();
            payload.put("id",userDB.getId());
            payload.put("name",userDB.getName());
            payload.put("password",userDB.getPassword());
            //生成JWT的令牌
            String token = JWTUtils.getToken(payload);

            //
            return R.ok().data("iat",JWTUtils.getIatAndExp().get("iat"))
                                .data("exp",JWTUtils.getIatAndExp().get("exp"))
                                .data("token",token)
                                .data("userInfo",user);


        }catch (Exception e){
//            map.put("state",false);
//            map.put("msg",e.getMessage());
            return R.setResult(ResponseEnum.WrongPassword).status("success");
        }

    }

    @ApiOperation(value = "用户初始化")
    @GetMapping("/user/init")
    public R test(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //处理自己业务逻辑
        String token = request.getHeader("access-token");
        DecodedJWT verify = JWTUtils.verify(token);

        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        String password = verify.getClaim("password").asString();
        User user = new User(id, name, password);

        log.info("用户id: [{}]",id);
        log.info("用户name: [{}]",name);


        return R.ok().msg("初始化成功")
                        .data("userInfo",user);
    }

    @ApiOperation("新增用户")
    @PostMapping("/user/save")
    public R save(
            @ApiParam(value = "用户对象",required = true)
            @RequestBody User user) {

//        if (true) {
//            throw new BusinessException(ResponseEnum.InsertErr);
//        }
        Object o = null;
        Assert.notNull(o,ResponseEnum.NullPointer);

        boolean isSaved = userService.save(user);
        if (isSaved) {
            return R.ok().msg("保存成功");
        }

        return R.error().msg("保存失败");

    }

    @ApiOperation("删除用户")
    @DeleteMapping("/user/remove/{name}")
    public R save(
            @ApiParam(value = "用户名字",required = true)
            @PathVariable String name) {
        boolean isDeleted = userService.deleteUser(name);
        if (isDeleted) {
            return R.ok().msg("删除成功");
        }


        return R.error().msg("删除失败");
    }

    @ApiOperation("查询所有用户")
    @GetMapping("/user/getAll")
    public R getAllUser() {
        List<User> users =  userService.findAllUser();
        for (int i = 0; i < 1000; i++) {
            log.info("hi, this is log info");
            log.warn("hi, this is log warn");
            log.error("hi, this is log error");
        }



        return R.ok().data("userInfo",users).msg("查询成功");
    }




}
